package cash_access;

import java.io.IOException;

import mware_lib.ManagerSkeleton;
import mware_lib.RemoteException;
import mware_lib.namensdienst.communication.ObjectConnection;
import mware_lib.namensdienst.messages.AccReqMsg;
import mware_lib.namensdienst.messages.AccRetMsg;

public class AccountWorker implements Runnable{

	private ObjectConnection myConnection;
	private ManagerSkeleton ms;

	public AccountWorker(ObjectConnection myConnection, ManagerSkeleton ms) {
		this.myConnection = myConnection;
		this.ms = ms;
	}

	public void run() {

		Object msg;
		try {
			msg = myConnection.receive();

			AccRetMsg accMsg = null;

			if(msg instanceof AccReqMsg){
				AccReqMsg reqMsg = (AccReqMsg)msg;
				Account acc = (ms.getAccountTable()).get(reqMsg.getKontoID());

				if(reqMsg.getMethod().equals("getBalance")){
					accMsg = new AccRetMsg(acc.getBalance());
				}else if(reqMsg.getMethod().equals("deposit")){
					try{
						acc.deposit(reqMsg.getAmount());
						accMsg = new AccRetMsg(0);
					}catch (RuntimeException  e){
						accMsg = new AccRetMsg(0, false, e.getMessage(), "Runtime");
					}
				}else if(reqMsg.getMethod().equals("withdraw")){
					try{
						acc.withdraw(reqMsg.getAmount());
						accMsg = new AccRetMsg(0, true);
					}catch (OverdraftException e) {
						accMsg = new AccRetMsg(0, false, e.getMessage(), "Overdraft");
					}catch (RuntimeException  e){
						accMsg = new AccRetMsg(0, false, e.getMessage(), "Runtime");
					}
					
				}else{
					System.out.println("BankSkeleton receive: Methodtyp unbekannt");
				}
			}

			myConnection.send(accMsg);

			myConnection.close();

		} catch (ClassNotFoundException e) {
			throw new RemoteException(e.getClass().toString() + ": " + e.getMessage(), e);
		} catch (IOException e) {
			throw new RemoteException(e.getClass().toString() + ": " + e.getMessage(), e);
		}

	}
}
